package com.hebeiboruan.controller.system;
import com.hebeiboruan.testsystem.common.exception.example.ExampleResultEnum;
import com.hebeiboruan.example.service.ExampleService;
import com.hebeiboruan.testsystem.entity.DTO.SearchExampleDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hebeiboruan.example.listener.ExampleListener;
import com.hebeiboruan.testsystem.entity.Example;
import com.hebeiboruan.common.HttpMessage;
import com.hebeiboruan.common.exception.CommonException;
import java.time.LocalDateTime;
import com.hebeiboruan.common.exception.ServiceResultEnum;

import javax.servlet.http.HttpServletRequest;
import com.alibaba.excel.EasyExcel;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.util.Arrays;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hebeiboruan.common.uitl.LoggerUtil;
@RestController
@RequestMapping("/example")
public class ExampleController {
    private static Logger log = LoggerFactory.getLogger(ExampleController.class);
    private ExampleService exampleService;

    @Autowired
    public void setExampleService(ExampleService exampleService) {
    this.exampleService = exampleService;
    }

    @GetMapping("/getAllExample/{page}/{limit}")
    public HttpMessage getAllExample(@PathVariable Integer page,@PathVariable Integer limit){
        HttpMessage.isBlank(page,limit);
        Page<Example> exampleModel = exampleService.page(new Page<>(page, limit), new QueryWrapper<Example>().isNull("example_model"));
        exampleModel.getRecords().forEach(item->{
            List<Example> exampleModel1 = exampleService.list(new QueryWrapper<Example>().eq("example_model", item.getExampleNo()));
            exampleModel1.forEach(item2->{
                List<Example> exampleModel2 = exampleService.list(new QueryWrapper<Example>().eq("example_model", item2.getExampleNo()));
                item2.setChildren(exampleModel2);
            });
            item.setChildren(exampleModel1);
        });
        return  HttpMessage.data(exampleModel);
    }
    @GetMapping("/getAllExample")
    public HttpMessage getAllExample(){
        return  HttpMessage.data(exampleService.list());
    }
    @PostMapping("/searchExample")
    public HttpMessage searchUser(SearchExampleDTO search){
    HttpMessage.isBlank(search.getPage(),search.getLimit());
    QueryWrapper<Example> wrapper=new QueryWrapper<>();
    return  HttpMessage.data(exampleService.page(new Page<>(search.getPage(),search.getLimit()),wrapper));
    }
    @PutMapping("/addExample")
    public HttpMessage addExample(Example example, HttpServletRequest request){
        HttpMessage.isBlank();
        try {
            exampleService.save(example);
            return  HttpMessage.result(ServiceResultEnum.INSERT_TRUE);
        }catch (Exception e){
            LoggerUtil.webError(e,request,log);
            throw new CommonException(ServiceResultEnum.INSERT_ERROR,e);
        }
    }
    @PostMapping("/editExample")
    public HttpMessage editExample(Example example, HttpServletRequest request){
        HttpMessage.isBlank();
        try {
            exampleService.updateById(example);
            return  HttpMessage.result(ServiceResultEnum.UPDATE_TRUE);
        }catch (Exception e){
            LoggerUtil.webError(e,request,log);
            throw new CommonException(ServiceResultEnum.UPDATE_ERROR,e);
        }
    }
    @DeleteMapping("/removeExample/{exampleNo}")
    public HttpMessage removeExample(@PathVariable Integer exampleNo,HttpServletRequest request){
        HttpMessage.isBlank(exampleNo);
        try {
            exampleService.removeById(exampleNo);
            return  HttpMessage.result(ServiceResultEnum.REMOVE_TRUE);
        }catch (Exception e){
            LoggerUtil.webError(e,request,log);
            throw new CommonException(ServiceResultEnum.REMOVE_ERROR,e);
        }

    }
    @DeleteMapping("/batchRemoveExample/{id}")
    public HttpMessage batchRemoveExample(@PathVariable String id){
        HttpMessage.isBlank(id);
        try{
            exampleService.removeBatchByIds(Arrays.asList(id.split(",")));
            return  HttpMessage.result(ServiceResultEnum.REMOVE_TRUE);
        }catch (Exception e){
            throw new CommonException(ServiceResultEnum.BATCH_REMOVE_ERROR,e);
        }

    }

    @PostMapping("/batchAddExample")
    public HttpMessage batchAddExample(@RequestParam("example")List<MultipartFile> example) {
        example.forEach(file->{
                try {
                    EasyExcel.read(file.getInputStream(), Example.class, new ExampleListener(exampleService)).sheet().doRead();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        return  HttpMessage.result(ServiceResultEnum.BATCH_INSERT_TRUE);
    }

    @PostMapping("/batchOutExample")
    public void batchOutExample(@RequestParam("example") List<String> example, HttpServletResponse response) throws IOException {
        try{
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        //防止乱码
        String fileName ="D:/"+ URLEncoder.encode("exampleData:"+LocalDateTime.now().toString(), "UTF-8").replaceAll("\\+", "%20")+".xlsx";
        List<Example> exampleData=new ArrayList<>();
            example.forEach(item->{
                try {
                    exampleData.add( new ObjectMapper().readValue(item,Example.class));
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            });
                response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

                EasyExcel.write(response.getOutputStream(), Example.class).autoCloseStream(Boolean.FALSE).sheet("数据").doWrite(exampleData);

        }catch (Exception e){
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            response.getWriter().println(HttpMessage.result(ServiceResultEnum.BATCH_OUT_ERROR));
        }
    }
    @PostMapping("/runExample")
    public HttpMessage runExample(Example example){
        switch (example.getExampleType()){
            case 1:
                exampleService.runExample(example);
                break;
            case 2:
                exampleService.runFunction(example);
                break;
            case 3:
                exampleService.runModel(example);
                break;
        }
        if(example.getExampleResult().equals(1)){
            return HttpMessage.result(ExampleResultEnum.RESULT_TRUE);
        }else{
            return HttpMessage.result(ExampleResultEnum.RESULT_ERROR);
        }
    }
}


